package com.kfgj.hkp.common.auth;

import com.kfgj.hkp.common.exception.BusinessException;
import com.kfgj.hkp.common.logging.Logger;
import com.kfgj.hkp.common.logging.LoggerFactory;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;

public class Token {

    private Logger logger = LoggerFactory.getLogger(Token.class);

    private static final String tokenCharset = "utf-8";

    /**
     * 用户编号
     */
    private String userCode;

    private String authKey;

    private long timestamp = System.currentTimeMillis();

    private long expireSecond = 0;
    //这个是超时时间的毫秒值
    private long expireTime = 0;

    public Token() {

    }

    public static Token parseToken(String base64String) {
        Token token = null;

        if (StringUtils.isNotEmpty(base64String)) {
            try {
                base64String = URLDecoder.decode(base64String,tokenCharset);
            } catch (UnsupportedEncodingException e) {
                throw new BusinessException("Token 解析异常",e);
            }
            byte[] bts = Base64.decodeBase64(base64String);
            String tokenStr = new String(bts, Charset.forName(tokenCharset));
            String[] tks = tokenStr.split(",");
            if (tks.length == 5 && StringUtils.isNumeric(tks[2])
                    && StringUtils.isNumeric(tks[3]) && StringUtils.isNumeric(tks[4])) {
                token = new Token();
                token.setUserCode(tks[0]);
                token.setAuthKey(tks[1]);
                token.setTimestamp(Long.parseLong(tks[2]));
                token.setExpireSecond(Long.parseLong(tks[3]));
                token.setExpireTime(Long.parseLong(tks[4]));
            }
        }
        return token;
    }

    public Token(String userCode, String authKey) {
        this.userCode = userCode;
        this.authKey = authKey;
    }

    public Token(String userCode, String authKey, long expireSecond) {
        this.userCode = userCode;
        this.authKey = authKey;
        this.expireSecond = expireSecond;
        this.timestamp = System.currentTimeMillis();
        this.expireTime = this.timestamp + (expireSecond * 1000);
    }

    public byte[] toBytes() {
        String tokenStr = this.toString();
        byte[] bts = tokenStr.getBytes(Charset.forName(tokenCharset));
        return bts;
    }

    public String toBase64String() {
        byte[] bts = this.toBytes();
        try {
            return URLEncoder.encode(Base64.encodeBase64String(bts),tokenCharset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new BusinessException("Token 异常",e);
        }
    }


    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(userCode).append(",");
        sb.append(authKey).append(",");
        sb.append(timestamp).append(",");
        sb.append(expireSecond).append(",");
        sb.append(expireTime);
        return sb.toString();
    }

    /**
     * 查看token是否过期，如果当前时间戳大于指定时间戳就表示已经过期
     *
     * @return
     */
    public boolean isExpired() {

        long exp = this.getExpireTime();

        /**
         * 如果是小于1的数就是不设置超时
         */
        if (this.getExpireSecond()<1){
            return false;
        }

        long cur = System.currentTimeMillis();
        return cur > exp ? true : false;
    }

    /**
     * @param expireSecond second
     */
    public void reloadExpireTime(long expireSecond) {

        this.expireSecond = expireSecond;

        this.timestamp = System.currentTimeMillis();

        this.expireTime = this.timestamp + (expireSecond * 1000);
    }

    public String getUserCode() {
        return userCode;
    }

    public String getAuthKey() {
        return authKey;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public long getExpireSecond() {
        return expireSecond;
    }

    public Long getExpireTime() {
        return expireTime;
    }

    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }

    public void setAuthKey(String authKey) {
        this.authKey = authKey;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public void setExpireSecond(long expireSecond) {
        this.expireSecond = expireSecond;
    }

    public void setExpireTime(long expireTime) {
        this.expireTime = expireTime;
    }
}
